import { NextFunction, Response } from "express";
import { LoggedInRequest } from "../types";
import { Token } from "../dao/Token";
import type { QueryError } from "mysql2"
import { serviceConfig } from "@Tea/model";
import { AppToken } from "../dao/AppToken";

export const checkToken = (req: LoggedInRequest, res: Response, next: NextFunction) => {
  const tokenHash = req.cookies[serviceConfig.systemTokenCode] as string
  
  const token = Token.getInstance()
  const tokenObj = token.getToken(tokenHash)
  
  if (tokenObj == null) {
    res.status(401).send({
      code: 401,
      msg:"身份失效，请重新登录"
    })
    return
  }
  
  // 将缓存token内容挂载到req
  req.userInfo = tokenObj

  next()
}

export const checkAppToken = (req: LoggedInRequest, res: Response, next: NextFunction) => {
  const tokenHash = req.cookies['tea_online'] as string
  
  const token = AppToken.getInstance()
  const tokenObj = token.getToken(tokenHash)
  
  if (tokenObj == null) {
    res.status(401).send({
      code: 401,
      msg:"身份失效，请重新登录"
    })
    return
  }
  
  // 将缓存token内容挂载到req
  req.userInfo = tokenObj

  next()
}

export const checkError = (queryError: QueryError) => {
  const {errno, sqlState ,message} = queryError
  console.log("checkError:", queryError);
  
  switch (errno) {
    case 1052:
      return message
    case 1064:
      return  "sql语法错误"
    default:
      return 'sql操作未知错误'
  }
}